package top.codervan.yygh.msm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import top.codervan.yygh.common.result.Result;
import top.codervan.yygh.msm.service.MsmService;
import top.codervan.yygh.msm.utils.RandomUtil;

import java.util.concurrent.TimeUnit;

/**
 * @Author: van
 * @Date: 2022/2/23 15:37
 */
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 根据手机号码完成登录和注册功能
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis获取验证码。如果获取到，就返回ok
        //key 手机号(phone) value 验证码(code)
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //如果获取不到，就生成验证码，并整合短信服务进行发送
        code = RandomUtil.getSixBitRandom();
        System.out.println(code);
// TODO boolean isSend = msmService.send(phone,code);
        boolean isSend = true;
        if (isSend) {
            //生成验证码放入redis里面，并且设置有效时间
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return Result.ok().message("短信发送成功");
        }else {
            return Result.fail().message("短信发送失败");
        }
    }
}
